#include "Acceptor.h"
#include "Connection.h"

Acceptor::Acceptor(EventLoop* loop, const std::string &ip, const uint16_t port)
:loop_(loop), servsock_(createnonblocking()),acceptChannel_(loop_, servsock_.fd())
{
    //创建一个用于listen的socketfd
    //servsock_ = new Socket(createnonblocking());
    InetAddress servaddr(ip, port);

    servsock_.setreuseaddr(true);
    servsock_.settcpnodelay(true);
    servsock_.setreuseport(true);
    servsock_.setkeepalive(true);
    servsock_.bind(servaddr);
    servsock_.listen();//启动监听

    //acceptChannel_ = new Channel(loop_, servsock_.fd());//创建一个服务端listenfd和epoll的Channel对象
    //&servsock为&Channel::new_Connection的参数
    acceptChannel_.set_Read_CallBack(std::bind(&Acceptor::new_Connection, this));
    //这里没有设置边缘触发，默认用的是水平触发
    acceptChannel_.enable_Reading();   //将服务端套接字读事件放入红黑树
}


Acceptor::~Acceptor()
{
    //delete servsock_;
    //delete acceptChannel_;
}

//处理新客户端连接请求
void Acceptor::new_Connection()          
{
    InetAddress clientaddr;
    std::unique_ptr <Socket> clientsock(new Socket(servsock_.accept(clientaddr)));
    clientsock->set_IP_PORT(clientaddr);
    newConnectionCb_(std::move(clientsock));    //回调TcpServer类的函数
}

void Acceptor::setNewConnectionCb(std::function<void(std::unique_ptr <Socket>)> func)
{
    newConnectionCb_ = func;
}